// 从特定于 React 的入口点导入 RTK Query 方法
import { getStore, removeStore } from "@/utils/storage";
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

export interface resBaseType<T> {
    code: number;
    message: string | null;
    data: {
        count?: number,
        rows?: T[],
    };
}
export interface Goods {
    id?: number,
    name?: string,
    price?: number,
    introduce?: string,
    pre_price?: number,
    num?: number,
    bz?: string
}
export type GoodsType = resBaseType<Goods>;

export interface menu {
    bz: string,
    children: menu[],
    create_user: string,
    createdAt: string,
    del_marker: number,
    icon_url: string,
    id: number,
    level_string: string,
    name: string,
    order: number,
    outer_url: string,
    parent_id: number,
    router_param: string,
    router_param_val: string,
    router_type: number,
    router_url: string,
    update_user: number,
    updatedAt: number,
}
export interface menuType {
    code: number,
    message: string,
    data: menu[],
}
export interface loginType {
    code: number,
    message: string,
    data: {
        tokens: {
            accessToken: string,
            accessTokenExp: string,
            refreshToken: string,
            tokenType: string
        },
        userInfo: {
            username: string,
            name: string,
            userId: string,
        }
    },
}
export type requestType = {
    username?: string;
    password?: string;
    remember?: string
}

import type {
    BaseQueryFn,
    FetchArgs,
    FetchBaseQueryError,
} from '@reduxjs/toolkit/query'
import { message } from "antd";

const baseQuery = fetchBaseQuery({
    baseUrl: '/api',
    prepareHeaders: (headers) => {
        let tokenString = getStore('tokens');// 获取token
        if (tokenString) {
            const tokenArray = tokenString.substring(1, tokenString.length - 1).replace(/\"/g, "").split(",");
            let tokens: any = {}
            for (let item of tokenArray) {
                let items = item.split(":");
                tokens[items[0]] = items[1];
            }
            //设置请求头token
            let accessToken = tokens.accessToken,
                tokenType = tokens.tokenType;
            headers.set('Authorization', `${tokenType} ${accessToken}`);
        }
        return headers;
    },
    // paramsSerializer: (params) => {
    //     return JSON.stringify(params);
    // }
    // 可选：请求超时设置
    // timeout: 3000, // 请求超时时间（毫秒）
});
const baseQueryWithReauth: BaseQueryFn<
    string | FetchArgs,
    unknown,
    FetchBaseQueryError
> = async (args, api, extraOptions) => {
    let result = await baseQuery(args, api, extraOptions);
    if (result.error && result.error.status === 401) {
        // try to get a new token
        // const refreshResult = await baseQuery('/refreshToken', api, extraOptions);
        // if (refreshResult.data) {
        //     // store the new token
        //     api.dispatch(tokenReceived(refreshResult.data))
        //     // retry the initial query
        //     result = await baseQuery(args, api, extraOptions)
        // } else {
        //     api.dispatch(loggedOut())
        // }
    } else {
        const { code, message: msg } = result.data as any;
        // let navigate = useNavigate();
        // loading - 1
        // useStore().setLoading(false); //关闭loading

        // 这里处理一些response 正常放回时的逻辑
        // showMessage('warning', msg);
        switch (code) {
            //自由约定不同状态码下前端的处理逻辑
            case -1:
                message.error(msg);
                break;
            // case 200:
            //     response.msg !== '' && notice(response.msg, 'message', 'success');
            //     return Promise.resolve(response);
            case 401:
                removeStore('tokens');
                removeStore('userInfo');
                removeStore('menu');
                // navigate('/logins/login', { replace: true });
                break;
            //     $router.replace('/logins/login');
            //     store.dispatch('SET_LOGOUT');
            case 4010:
                // $router.replace('/login?redirect=' + $router.currentRoute.fullPath);   //登录后跳转到上次退出的页面
                message.error(msg);
                //缓存token和用户信息
                removeStore('tokens');
                removeStore('userInfo');
                removeStore('menu');
                window.location.href = "/logins/login";
                // navigate('/logins/login', { replace: true });
                break;
            // $router.replace('/logins/login');
            // useStore().setLogout(); //退出系统
        }
    }
    return result
}

export interface role {
    id?: number,
    name: string,
    create_user?: string,
    update_user?: string,
    updatedAt?: string,
}
export interface searchType {
    name?: string
}
export type roleType = resBaseType<role>;

// 定义我们的单个 API Slice 对象
export const apiSlice = createApi({
    reducerPath: 'api',// 缓存减速器预计将添加到 `state.api` （已经默认 - 这是可选的）
    baseQuery: baseQueryWithReauth, // 我们所有的请求都有以 “/api” 开头的 URL
    tagTypes: ['good', 'role'],//指定数据的标签类型
    // “endpoints” 代表对该服务器的操作和请求
    endpoints: builder => ({
        //< >里面的泛型，第一个是请求返回数据的类型，第二个接收参数的数据类型
        loginSys: builder.mutation<loginType, requestType>({
            // 请求的 URL 是“/fakeApi/posts”
            query: (params) => ({
                method: "POST",
                url: "/login",
                body: params
            })
        }),
        // loginOut:builder.mutation<>
        getMenuList: builder.mutation<menuType, void>({
            query: () => ("/userMenuList")
        }),
        // `getGoods` endpoint 是一个返回数据的 “Query” 操作
        getGoods: builder.query<GoodsType, void>({
            // 请求的 URL 是“/api/posts/goods/list”
            query: (filters) => ({
                method: 'POST',
                url: '/goods/list',
                body: filters
            }),
            //转换响应数据
            // transformResponse: (response:any)=>{
            //     return response.data;
            // },
            // keepUnusedDataFor:5,//设置数据缓存的时间，单位s，默认60s
            // providesTags: ['good']  //为数据打上标签，如果失效重新加载此数据
            providesTags: [
                {
                    type: 'good',
                    id: 'list',
                }
            ]
        }),
        getGoodDetil: builder.query<GoodsType, number>({
            query: (id) => ({
                method: 'GET',
                url: `/goods/detail?id=${id}`,
            }),
            providesTags: (result, error, arg) => [
                { type: 'good', id: arg }
            ]
        }),
        // providesTags: (result, error, arg) => [{ type: 'Post', id: arg }]
        addGood: builder.mutation<void, Goods>({
            // 我们在 mutation 成功时返回的数据
            query: (initialPost) => ({
                method: 'POST',
                url: '/goods/add',
                body: initialPost
            }),
            invalidatesTags: [{
                type: 'good',
                id: "list",
            }]   //使标签失效，重新加载数据
        }),
        modifysGood: builder.mutation<Goods, Goods>({
            query: (initialPost) => ({
                method: 'PUT',
                url: '/goods/update',
                body: initialPost
            }),
            // invalidatesTags: ['good']  //使标签失效，重新加载数据
            invalidatesTags: (result, error, arg) => [{ type: 'good', id: arg.id }, { type: 'good', id: 'list' }]
            //使标签失效，重新加载数据
        }),
        searchRole: builder.query<roleType, searchType>({
            query: (params) => ({
                method: 'post',
                url: '/role/list',
                body: params
            }),
            providesTags: [
                {
                    type: 'role',
                    id: 'list',
                }
            ]
        }),
        addRole: builder.mutation<void, role>({
            query: (params) => ({
                method: "post",
                url: '/role/add',
                body: params
            }),
            invalidatesTags: [{
                type: 'role',
                id: "list",
            }]   //使标签失效，重新加载数据
        }),
        editRole: builder.mutation<void, role>({
            query: (params) => ({
                method: "put",
                url: '/role/update',
                body: params
            }),
            invalidatesTags: [{
                type: 'role',
                id: "list",
            }]
            // invalidatesTags: (result, error, arg) => [{ type: 'role', id: arg.id }, { type: 'role', id: 'list' }]
            //使标签失效，重新加载数据
        }),
        deleteRole: builder.mutation<void, number | undefined>({
            query: (id) => ({
                method: "delete",
                url: `/role/delete?id=${id}`,
            }),
            invalidatesTags: [{
                type: 'role',
                id: "list",
            }]   //使标签失效，重新加载数据
        })

        //     { method: 'POST', path: '/role/add', func: fn_add },
        // { method: 'PUT', path: '/role/update', func: fn_update },
        // { method: 'DELETE', path: '/role/delete', func: fn_delete },
        // { method: 'POST', path: '/role/list', func: fn_list },
    })
});
// 为 `getGoods` Query endpoint 导出自动生成的 hooks
export const { useLoginSysMutation, useGetMenuListMutation,
    useGetGoodsQuery, useAddGoodMutation, useModifysGoodMutation, useGetGoodDetilQuery,
    useSearchRoleQuery, useAddRoleMutation, useDeleteRoleMutation, useEditRoleMutation } = apiSlice;